package ar.com.larctest.forms;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import ar.com.larctest.R;
import ar.com.larctest.adapters.ListViewMeasurementHorsesAdapter;
import ar.com.larctest.entities.temp.TMeasurementItem;
import ar.com.larctest.providers.MeasurementProvider;
import ar.com.larctest.providers.temp.MeasurementTempProvider;
import ar.com.larctest.utils.Constants;

public class MeasurementActivity extends Activity {
    private static final String TAG = "MeasurementActivity";
    private static final int MY_CHILD_ACTIVITY = 999;
    private static final int MY_CHILD_ACTIVITY_ADD = 998;

    private Handler mHandler;
    private boolean mCounterActive;
    ListView listViewMeasurementHorses;

    private List<TMeasurementItem> lstMeasurementHorses = new ArrayList<TMeasurementItem>();
    private ListViewMeasurementHorsesAdapter horsesItemsAdapter;
    TMeasurementItem selectedItem;


    public MeasurementActivity() {
        mHandler = new Handler();
    }

    //Enum for Menu Activity
    public enum MenuOptions {
        MENU_INIT(1), MENU_FINISH(2), MENU_LOAD(3), MENU_CONCLUSION(4), MENU_ADD(5), MENU_EXIT(6);
        private int code;
        MenuOptions(Integer code) {this.code = code;}
        public static MenuOptions valueOf(int itemId) {
            for (MenuOptions menuOption : MenuOptions.values()) {
                if (itemId == menuOption.code)
                    return menuOption;
            }
            return null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_measurement);

        listViewMeasurementHorses = (ListView) findViewById(R.id.lvMeasurementHorses);

        try
        {
            MeasurementTempProvider measurementTempProvider = new MeasurementTempProvider(this);
            lstMeasurementHorses = measurementTempProvider.getMeasurementItems();

            horsesItemsAdapter = new ListViewMeasurementHorsesAdapter(MeasurementActivity.this, R.id.lvMeasurementHorses, lstMeasurementHorses);
            listViewMeasurementHorses.setAdapter(horsesItemsAdapter);
            listViewMeasurementHorses.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    for(TMeasurementItem measurementItem: lstMeasurementHorses)
                        measurementItem.setSelected(false);

                    selectedItem = lstMeasurementHorses.get(position);
                    selectedItem.setSelected(true);
                    horsesItemsAdapter.notifyDataSetChanged();
                }
            });

            mCounterActive = true;
            mHandler.post(mRunnable);

        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private final Runnable mRunnable = new Runnable() {
        public void run() {
            if (mCounterActive) {
                if (lstMeasurementHorses != null) {

                    MeasurementTempProvider measurementTempProvider = new MeasurementTempProvider(MeasurementActivity.this);

                    for(TMeasurementItem measurementItem: lstMeasurementHorses) {
                        if(measurementItem.getState().equals(Constants.STATE_FINISH_COACHING)) {
                            Integer minutes = Integer.parseInt(measurementItem.getTimeOut1().split(":")[0]);
                            Integer seconds = Integer.parseInt(measurementItem.getTimeOut1().split(":")[1]);

                            long totalTimeCountInMilliseconds = (minutes * 60 * 1000) + (seconds * 1000);
                            totalTimeCountInMilliseconds -= 1000;

                            measurementItem.setTimeOut1(String.format("%02d", (totalTimeCountInMilliseconds / 1000) / 60)
                                    + ":" + String.format("%02d", (totalTimeCountInMilliseconds / 1000) % 60));

                            if(totalTimeCountInMilliseconds == 0) {
                                measurementItem.setTimeOut1("00:00");
                                measurementItem.setState(Constants.STATE_MEASUREMENT_TIMEOUT);
                            }

                            measurementTempProvider.updateMeasurementItem(measurementItem);

                        }
                        else if(measurementItem.getState().equals(Constants.STATE_MEASUREMENT_1)) {
                            Integer minutes = Integer.parseInt(measurementItem.getTimeOut2().split(":")[0]);
                            Integer seconds = Integer.parseInt(measurementItem.getTimeOut2().split(":")[1]);

                            long totalTimeCountInMilliseconds = (minutes * 60 * 1000) + (seconds * 1000);
                            totalTimeCountInMilliseconds -= 1000;

                            measurementItem.setTimeOut2(String.format("%02d", (totalTimeCountInMilliseconds / 1000) / 60)
                                    + ":" + String.format("%02d", (totalTimeCountInMilliseconds / 1000) % 60));

                            if(totalTimeCountInMilliseconds == 0) {
                                measurementItem.setTimeOut2("00:00");
                                measurementItem.setState(Constants.STATE_MEASUREMENT_TIMEOUT);
                            }

                            measurementTempProvider.updateMeasurementItem(measurementItem);

                        }
                        else if(measurementItem.getState().equals(Constants.STATE_MEASUREMENT_2)) {
                            Integer minutes = Integer.parseInt(measurementItem.getTimeOut3().split(":")[0]);
                            Integer seconds = Integer.parseInt(measurementItem.getTimeOut3().split(":")[1]);

                            long totalTimeCountInMilliseconds = (minutes * 60 * 1000) + (seconds * 1000);
                            totalTimeCountInMilliseconds -= 1000;

                            measurementItem.setTimeOut3(String.format("%02d", (totalTimeCountInMilliseconds / 1000) / 60)
                                    + ":" + String.format("%02d", (totalTimeCountInMilliseconds / 1000) % 60));

                            if(totalTimeCountInMilliseconds == 0) {
                                measurementItem.setTimeOut3("00:00");
                                measurementItem.setState(Constants.STATE_MEASUREMENT_TIMEOUT);
                            }

                            measurementTempProvider.updateMeasurementItem(measurementItem);
                        }
                    }
                    // notify that data has been changed
                    horsesItemsAdapter.notifyDataSetChanged();
                }
                // update every second
                mHandler.postDelayed(this, 1000);
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        try {
            menu.add(0, MenuOptions.MENU_INIT.code, 0, R.string.Measurement_Menu_Init);
            menu.add(0, MenuOptions.MENU_FINISH.code, 0, R.string.Measurement_Menu_Finish);
            menu.add(0, MenuOptions.MENU_LOAD.code, 0, R.string.Measurement_Menu_Load);
            menu.add(0, MenuOptions.MENU_CONCLUSION.code, 0, R.string.Measurement_Menu_Conclusion);
            menu.add(0, MenuOptions.MENU_ADD.code, 0, R.string.Measurement_Menu_AddHorse);
            menu.add(0, MenuOptions.MENU_EXIT.code, 0, R.string.Measurement_Menu_Exit);
            return super.onCreateOptionsMenu(menu);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean onOptionsItemSelected(MenuItem item)
    {
        if(item.getItemId() == Constants.MENU_EXIT)
        {
            AlertDialog.Builder alertDialogExit = new AlertDialog.Builder(this);
            alertDialogExit.setMessage(getString(R.string.exitWithoutSave))
                    .setCancelable(false)
                    .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            mCounterActive = false;
                            MeasurementActivity.this.finish();
                        }
                    })
                    .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            alertDialogExit.create();
            alertDialogExit.show();
        }
        else if(item.getItemId() == Constants.MENU_ADD) {
            Intent intentAddHorse = new Intent(this, PopUpListHorsesActivity.class);
            startActivityForResult(intentAddHorse, MY_CHILD_ACTIVITY_ADD);
        }
        else {
            if(selectedItem == null) {
                LayoutInflater inflater = getLayoutInflater();
                View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

                TextView text = (TextView) (layout != null ? layout.findViewById(R.id.text) : null);
                if (text != null) {
                    text.setText(getText(R.string.Horses_HorseRequired));
                }

                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);
                toast.show();
            }
            else {


                MenuOptions menuOptions = MenuOptions.valueOf(item.getItemId());

                switch (menuOptions) {
                    case MENU_INIT:
                        if(selectedItem.getState().equals(Constants.STATE_INIT)) {
                            MeasurementTempProvider measurementTempProvider = new MeasurementTempProvider(this);
                            selectedItem.setInitTime(new Date());
                            selectedItem.setState(Constants.STATE_COACHING);
                            measurementTempProvider.updateMeasurementItem(selectedItem);

                            horsesItemsAdapter.notifyDataSetChanged();
                        }
                        break;
                    case MENU_FINISH:
                        if(selectedItem.getState().equals(Constants.STATE_COACHING)) {
                            MeasurementTempProvider measurementTempProvider = new MeasurementTempProvider(this);
                            selectedItem.setFinishTime(new Date());
                            selectedItem.setState(Constants.STATE_FINISH_COACHING);
                            measurementTempProvider.updateMeasurementItem(selectedItem);

                            horsesItemsAdapter.notifyDataSetChanged();
                        }
                        break;
                    case MENU_LOAD:
                        if(selectedItem.getState().equals(Constants.STATE_FINISH_COACHING) ||
                                selectedItem.getState().equals(Constants.STATE_MEASUREMENT_1) ||
                                selectedItem.getState().equals(Constants.STATE_MEASUREMENT_2))
                        {
                            Intent intentLoadData = new Intent(this, PopUpMeasurementActivity.class);
                            intentLoadData.putExtra("actualMeasurement", selectedItem.getState());
                            intentLoadData.putExtra("actualHorse", selectedItem.getIdHorse());
                            startActivityForResult(intentLoadData, MY_CHILD_ACTIVITY);
                        }
                        else if(selectedItem.getState().equals(Constants.STATE_MEASUREMENT_3))
                        {
                            Intent intentLoadData = new Intent(this, PopUpFinalMeasurementActivity.class);
                            intentLoadData.putExtra("actualHorse", selectedItem.getIdHorse());
                            startActivityForResult(intentLoadData, MY_CHILD_ACTIVITY);
                        }
                        break;
                    case MENU_CONCLUSION:
                        MeasurementProvider measurementProvider = new MeasurementProvider(this);
                        Boolean result = measurementProvider.copyTempMeasurementData();
                        if(!result) {
                            LayoutInflater inflater = getLayoutInflater();
                            View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

                            TextView text = (TextView) (layout != null ? layout.findViewById(R.id.text) : null);
                            if (text != null) {
                                text.setText(getText(R.string.Measurement_Error_SaveMeasurement));
                            }

                            Toast toast = new Toast(getApplicationContext());
                            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                            toast.setDuration(Toast.LENGTH_LONG);
                            toast.setView(layout);
                            toast.show();
                        }

                        break;
                    default:
                        break;
                }
            }
        }

        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
            case (MY_CHILD_ACTIVITY):
                if (resultCode == Activity.RESULT_OK) {
                    if(selectedItem.getState().equals(Constants.STATE_FINISH_COACHING))
                        selectedItem.setState(Constants.STATE_MEASUREMENT_1);
                    else if(selectedItem.getState().equals(Constants.STATE_MEASUREMENT_1))
                        selectedItem.setState(Constants.STATE_MEASUREMENT_2);
                    else if(selectedItem.getState().equals(Constants.STATE_MEASUREMENT_2))
                        selectedItem.setState(Constants.STATE_MEASUREMENT_3);
                    else if(selectedItem.getState().equals(Constants.STATE_MEASUREMENT_3))
                        selectedItem.setState(Constants.STATE_MEASUREMENT_FINAL_DATA);

                    horsesItemsAdapter.notifyDataSetChanged();
                }
                break;

            case MY_CHILD_ACTIVITY_ADD:
                if (resultCode == Activity.RESULT_OK) {
                    horsesItemsAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

            TextView text = (TextView) (layout != null ? layout.findViewById(R.id.text) : null);
            text.setText(getText(R.string.disabledFunction));

            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(layout);
            toast.show();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
